package com.heaboy.emaidemo1.config;

import com.heaboy.emaidemo1.config.MailSenderInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 多邮箱发送器
 * 实现轮询发送策略
 */
@Slf4j
@Component
public class MultiEmailSender {
    
    @Autowired
    private MultiEmailProperties properties;
    
    private List<EmailSender> emailSenders;
    private AtomicInteger currentIndex = new AtomicInteger(0);
    
    @PostConstruct
    public void init() {
        initEmailSenders();
    }
    
    /**
     * 初始化邮箱发送器列表
     */
    private void initEmailSenders() {
        emailSenders = new ArrayList<>();
        
        if (properties.getSenders() != null) {
            for (EmailConfig config : properties.getSenders()) {
                if (config.isEnabled()) {
                    emailSenders.add(new EmailSender(config));
                    log.info("初始化邮箱发送器: {} - {}", config.getName(), config.getUsername());
                }
            }
        }
        
        log.info("共初始化 {} 个邮箱发送器", emailSenders.size());
    }
    
    /**
     * 发送邮件（轮询策略）
     */
    public boolean sendEmail(MailSenderInfo mailInfo) {
        if (emailSenders.isEmpty()) {
            log.error("没有可用的邮箱发送器");
            return false;
        }
        
        int retryTimes = properties.getStrategy().getRetryTimes();
        
        for (int i = 0; i < retryTimes; i++) {
            // 获取下一个邮箱发送器
            EmailSender sender = getNextSender();
            
            if (sender != null && sender.isAvailable()) {
                log.info("尝试使用邮箱发送: {} - {}", 
                    sender.getConfig().getName(), sender.getConfig().getUsername());
                
                if (sender.send(mailInfo)) {
                    return true;
                }
            }
        }
        
        log.error("所有邮箱发送失败，重试次数: {}", retryTimes);
        return false;
    }
    
    /**
     * 获取下一个邮箱发送器（轮询）
     */
    private EmailSender getNextSender() {
        if (emailSenders.isEmpty()) {
            return null;
        }
        
        int index = currentIndex.getAndIncrement() % emailSenders.size();
        return emailSenders.get(index);
    }
    
    /**
     * 发送邮件到单个收件人
     */
    public boolean sendToSingleUser(String toEmailAddress, String title, String content) {
        MailSenderInfo mailInfo = new MailSenderInfo();
        mailInfo.setToAddress(toEmailAddress);
        mailInfo.setSubject(title);
        mailInfo.setContent(content);
        
        return sendEmail(mailInfo);
    }
    
    /**
     * 发送邮件到多个收件人
     */
    public boolean sendToMultipleUsers(List<String> toEmailAddresses, String title, String content) {
        if (toEmailAddresses == null || toEmailAddresses.isEmpty()) {
            log.error("收件人列表为空");
            return false;
        }
        
        String toAddresses = String.join(",", toEmailAddresses);
        
        MailSenderInfo mailInfo = new MailSenderInfo();
        mailInfo.setToAddress(toAddresses);
        mailInfo.setSubject(title);
        mailInfo.setContent(content);
        
        return sendEmail(mailInfo);
    }
    
    /**
     * 获取当前可用的邮箱数量
     */
    public int getAvailableSenderCount() {
        return (int) emailSenders.stream().filter(EmailSender::isAvailable).count();
    }
    
    /**
     * 获取所有邮箱信息
     */
    public List<EmailConfig> getAllEmailConfigs() {
        List<EmailConfig> configs = new ArrayList<>();
        for (EmailSender sender : emailSenders) {
            configs.add(sender.getConfig());
        }
        return configs;
    }
}

